
$(document).ready(function(){
	$('div.documentListHeader').click(function() {
		$(this).next().toggle();
	});
	
});	

/**
 * Show inpatientes queues for doctor
 * @return nothing 
 */
function viewDoctorQueue() {	
	// TODO REVIEW Trung Nguyen 2009-07-21
	// Element Id defined by Case-camel style	
	var emergencyTable = $('table#tableEmergencyQueue');	
	var recoveryTable = $('table#tableRecoveryQueue');
	$.ajax({
		type:		"GET",
		url:		"../EmergencyInPatient/RenderDoctorQueuesAjax?set_ajax_view",
		data:		"",		
		dataType:   "json",				
		beforeSend: function() {
		$('div#reload').hide();
		$('div#innerLoading').show();
	},
	complete: function() {
		$('div#reload').show();
		$('div#innerLoading').hide();				
	},									
	success: 	function(data) {		
		// TODO REVIEW Trung Nguyen 2009-07-21
		// Element Id defined by Case-camel style

		if (data.emergency.body != null) {
			fillTableData(emergencyTable, data.emergency.body);
			fillTotalTableData($('div#emergencyQueue'), data.emergency.total_table);

		}

		if (data.recovery.body != null) {
			fillTableData(recoveryTable, data.recovery.body);
			fillTotalTableData($('div#recoveryQueue'), data.recovery.total_table);

		}
        $('#patientNumberField').html(data.patientNumber);
        
		triggerUpdate(emergencyTable, recoveryTable);
	}
	});
}

function fillTotalTableData(parentDiv, data) {
	$('table.total_table', parentDiv).remove();
	parentDiv.append(data);
	parentDiv.children('table:last-child').addClass('total_table');
}

function fillTableData(table, data) {
	$('tbody', table).children().remove();	
	$('tbody', table).append(data);
	table.find('tr:last-child').addClass('last');

	if ($('tbody tr', table).length > 0) {
		table.show();
	} else {
		table.hide();
	}	
}

function triggerUpdate(emergencyTable, recoveryTable) {		
	emergencyTable.trigger('update');	
	recoveryTable.trigger('update');			
}
function displayEmerInstantInfo(ticketId) {
	displayInstantInfo(ticketId,10);
}

function displayRecInstantInfo(ticketId) {
	displayInstantInfo(ticketId,9);
}
/**
* Display instant info panel when user click instant info button.
* @param ticketId
* @param colspan number of table columns to span
* @return nothing
* 
*/
function displayInstantInfo(ticketId, colspan) {
	if ($('#' + ticketId).val() == 'true'){
		$('#' + ticketId + 'Row').remove();
		$('#' + ticketId).val('hidden');
		return;
	} 
	if ($('#' + ticketId).val() == 'hidden'){		
		$('#' + ticketId).val('true');		
	}
	$.ajax({
		type:		"GET",
		url:		"../PatientInfo/InstantInfoAjax?set_ajax_view",
		data:		"ticketId=" + ticketId,		
		dataType:   "json",
		success: 	function(data) {		
		$('tr#' + ticketId).after(data);
		$('tr#' + ticketId + 'Row td').attr('colspan',colspan);

		$('div#' + ticketId + 'InstantInfo').tabs({
			select: function(event, ui) {

			switch (ui.index) {
			case 0:
				loadPatientInfo(ticketId);

				break;
			case 1:				
				loadGeneralDiagnosis(ticketId);
				break;
			case 2:				
				loadLabAssignPanel(ticketId, 0);
				break;
		    case 3:
                loadRadiologyAssignmentPanel(ticketId)
			default:
				break;
			}



		}
		});

		loadPatientInfo(ticketId);


	}
	});	

	$('#' + ticketId).val('true');
}
function loadPatientInfo(ticketId) {
	$.ajax({
		type:		"GET",
		url:		"../PatientInfo/LoadPatientInfoAjax?set_ajax_view",
		data:		"ticketId=" + ticketId,		
		dataType:   "json",
		success: 	function(data) {			
		if (data.error.code == 0) {
			$('div#' + ticketId + 'InstantInfo-0').html(data.result);

		} else {
			displayError(data.error.mess);				
		}

	}
	});	


}
function displayError(errorMess) {
	var buttons = {};
	buttons[_('Close')] = function() {
		$(this).dialog('close');		
	};
	generalDialog(null,_("Error"),errorMess,'error',{
		autoOpen: true,			
		bgiframe: true,
		resizable: true,
		modal: true,							
		buttons: buttons
	});
}

function showMessage(targetId, message, status) {	
	if (status == 'success') {
		$('#' + targetId).css('color', 'green').text(message);
	} else if (status == 'error') {
		$('#' + targetId).css('color', 'red').text(message);		
	}

}
function loadGeneralDiagnosis(ticketId) {

	$.ajax({
		type:		"GET",
		url:		"../GeneralDiagnosis/loadGeneralDiagnosisAjax?set_ajax_view",
		data:		"ticketId=" + ticketId,		
		dataType:   "json",
		success: 	function(data) {			
		if (data.error.code == 0) {
			$('div#' + ticketId + 'InstantInfo-1').html(data.result);

		} else {
			displayError(data.error.mess);				
		}

	}
	});	

}

function resetStatusMess($ticketId) {
	$('#statusMessage' + ticketId).html('');
	$('#resultMessage' + ticketId).html('');

}

function vitalSignDateTimeValidation(ticketId) {
	if (!checkMonth($('#vitalSign' + ticketId + '_mm'),true,'','#statusMessage' + ticketId)) {
		$('#statusMessage' + ticketId).show();
		return false;
	} 

	if (!checkDay($('#vitalSign' + ticketId + '_dd'),true,'','#statusMessage' + ticketId)) {
		$('#statusMessage' + ticketId).show();	
		return false;
	}	
	if (!checkHour($('#vitalSignTime' + ticketId), true, '', 'statusMessage' + ticketId)) {
		$('#statusMessage' + ticketId).show();	
		return false;
	}

	var res 	= 	checkDate($('#vitalSign' + ticketId + '_yyyy'),
			$('#vitalSign' + ticketId + '_mm'),
			$('#vitalSign' + ticketId + '_dd'), true, '', '#statusMessage' + ticketId, false);	

	if(!res){	
		$('#statusMessage' + ticketId).show();
		return false;
	}
	$('#statusMessage' + ticketId).html('');
	return true;
}
/**
* Add vital sign for a given patient.
* @param ticketId
* @param patientId
* @return
*/
function addVitalSign(ticketId, patientId) {
	if (vitalSignDateTimeValidation(ticketId) == false) {
		return;
	}

	$('#vitalSignPulse' + ticketId).val('');
	$('#vitalSignBps' + ticketId).val('');
	$('#vitalSignBpd' + ticketId).val('');
	$('#vitalSignRespiratory' + ticketId).val('');
	$('#vitalSignTemperature' + ticketId).val('');
	$('#vitalSignSp02' + ticketId).val('');
	var dt=new Date();
	var second = (dt.getSeconds() < 10 ? '0' + dt.getSeconds(): dt.getSeconds());

	examineTime = $('#vitalSign' + ticketId + '_yyyy').val() 
	+ '-' 
	+ $('#vitalSign' + ticketId + '_mm').val()
	+ '-'
	+ $('#vitalSign' + ticketId + '_dd').val()
	+ ' '
	+ $('#vitalSignTime' + ticketId).val()
	+ ':'
	+ second;

	$.ajax({
		type:		"GET",
		url:		"../GeneralDiagnosis/addVitalSign?set_ajax_view",
		data:		"patientId=" + patientId + "&examineTime=" + examineTime,		
		dataType:   "json",
		success: 	function(data) {
		if (data.error.code == 0) {
			addDatePickerTime('#vitalSign' + ticketId + '_dd',
					'#vitalSign' + ticketId + '_mm',
					'#vitalSign' + ticketId + '_yyyy',
					'#vitalSignTime' + ticketId,false,false,true);

			reloadVitalSign(ticketId, patientId, data.result.vitalSignId, true);
		} else {
			displayError(data.error.mess);
		}			
	}
	});


}
function reloadVitalSign(ticketId, patientId, selectedVitalSignId, selectFirst) {
	$.ajax({
		type:		"GET",
		url:		"../GeneralDiagnosis/ListVitalSign?set_ajax_view",
		data:		"patientId=" + patientId,		
		dataType:   "json",
		success: 	function(data) {
		if (data.error.code == 0) {				
			var listOfVitalSign = data.result.listVitalSign;
			var listVitalSignHtml = '';
			var selected;
			for ( var index = 0; index < listOfVitalSign.length; index++) {
				vitalSign = listOfVitalSign[index];	
				if (selectFirst == true && index == 0) {
					selected = "selected='selected'";
					
				} else if (selectFirst == false && selectedVitalSignId == vitalSign.vital_sign_id) {
					selected = "selected='selected'";

				} else {
					selected = '';

				}
				listVitalSignHtml += '<option ' 
					+ 'vitalSignTime="'	+ vitalSign.examine_time + '" '
					+ 'value="' + vitalSign.vital_sign_id + '" '
					+ 'vitalSignPusle="' + vitalSign.pulse + '" '
					+ 'vitalSignBps="' + vitalSign.blood_presure_s + '" '
					+ 'vitalSignBpd="' + vitalSign.blood_presure_d + '" '
					+ 'vitalSignRespiratory="' + vitalSign.respiratory_rate + '" '
					+ 'vitalSignTemperature="' + vitalSign.temperature + '" '
					+ 'vitalSignSp02="' + vitalSign.sp02 + '" '
					+ selected 
					+ ' >' + vitalSign.examine_time + '</option>'
			}
			$('#vitalSignList' + ticketId).html(listVitalSignHtml);
			fillVitalSign(ticketId, 'vitalSignList' + ticketId);
		} else {
			displayError(data.error.mess);
		}			
	}
	});

}
function fillVitalSign(ticketId, vitalSignListId) {
	var selected = $('#' + vitalSignListId + ' :selected');
	if (selected != null) {         
		$('#vitalSignPulse' + ticketId).val(selected.attr('vitalSignPusle'));
		$('#vitalSignBps' + ticketId).val(selected.attr('vitalSignBps'));
		$('#vitalSignBpd' + ticketId).val(selected.attr('vitalSignBpd'));
		$('#vitalSignRespiratory' + ticketId).val(selected.attr('vitalSignRespiratory'));
		$('#vitalSignTemperature' + ticketId).val(selected.attr('vitalSignTemperature'));
		$('#vitalSignSp02' + ticketId).val(selected.attr('vitalSignSp02'));
	}
}
function submitDelVitalSign(ticketId, vitalSignId, patientId) {
	$.ajax({
		type:		"GET",
		url:		"../GeneralDiagnosis/delVitalSign?set_ajax_view",
		data:		"vitalSignId=" + vitalSignId,		
		dataType:   "json",
		success: 	function(data) {
		if (data.error.code == 0) {
			//loadGeneralDiagnosis(ticketId);
			reloadVitalSign(ticketId, patientId, 0, true);
		} else {
			displayError(data.error.mess);
		}			
	}
	});

}
function delVitalSign(ticketId, patientId) {

	var vitalSignId = $("select#vitalSignList" + ticketId + " :selected").val();
	if (vitalSignId != null && $.trim(vitalSignId) != '') {
		promptConfirm(_("Delete"),_('Are you sure to delete this vital sign?'), function() {

			submitDelVitalSign(ticketId, vitalSignId, patientId); 
			return true;
		},'YesNo','warn',_('No'));
	}
	
	

}
function vitalSignSaveValidation(ticketId) {
	var lcInt = locale(decimalPoint, thousandSep, 0);
	var lcFloat = locale(decimalPoint, thousandSep, 1);

		
	if (!validateNumberByLocal($('#vitalSignPulse' + ticketId), lcInt, false, null, "statusMessage" + ticketId)) {
		return false;
	}
	if (!validateNumberByLocal($('#vitalSignBpd' + ticketId), lcInt, false, null, "statusMessage" + ticketId)) {
		return false;
	}
	if (!validateNumberByLocal($('#vitalSignBpd' + ticketId), lcInt, false, null, "statusMessage" + ticketId)) {
		return false;
	}
	if (!validateNumberByLocal($('#vitalSignRespiratory' + ticketId), lcInt, false, null, "statusMessage" + ticketId)) {
		return false;
	}
	if (!validateNumberByLocal($('#vitalSignTemperature' + ticketId), lcFloat, false, null, "statusMessage" + ticketId)) {
		return false;
	}
	if (!validateNumberByLocal($('#vitalSignSp02' + ticketId), lcFloat, false, null, "statusMessage" + ticketId)) {
		return false;
	}
		
	return true;

}
function saveVitalSign(ticketId, patientId, vitalSignId) {
	if (vitalSignSaveValidation(ticketId) == false) {
		return;
	}
	var lcInt = locale(decimalPoint, thousandSep, 0);
	var lcFloat = locale(decimalPoint, thousandSep, 1);

	var vitalSignPulse = parseLcNum($('#vitalSignPulse' + ticketId).val(),lcInt);
	var vitalSignBps = parseLcNum($('#vitalSignBps' + ticketId).val(),lcInt);
	var vitalSignBpd = parseLcNum($('#vitalSignBpd' + ticketId).val(),lcInt);
	var vitalSignRespiratory = parseLcNum($('#vitalSignRespiratory' + ticketId).val(),lcInt);
	var vitalSignTemperature = parseLcNum($('#vitalSignTemperature' + ticketId).val(),lcFloat);
	var vitalSignSp02 = parseLcNum($('#vitalSignSp02' + ticketId).val(),lcFloat);
	
	//validate vitalSignBp
	if(!validateBP($('#vitalSignBps'+ticketId), $('#vitalSignBpd'+ticketId), $('#resultMessage'+ticketId))){
		return;
	}

	var paras = "ticketId=" + ticketId
	+ "&vitalSignId=" + vitalSignId
	+ "&vitalSignPulse=" + vitalSignPulse
	+ "&vitalSignBps=" + vitalSignBps
	+ "&vitalSignBpd=" + vitalSignBpd
	+ "&vitalSignRespiratory=" + vitalSignRespiratory
	+ "&vitalSignTemperature=" + vitalSignTemperature
	+ "&vitalSignSp02=" + vitalSignSp02;

	

	$.ajax({
		type:		"GET",
		url:		"../GeneralDiagnosis/SaveVitalSign?set_ajax_view",
		data:		paras,		
		dataType:   "json",
		beforeSend:	function() {
			$('#resultMessage' + ticketId).html('');				
		},
		success: 	function(data) {
		if (data.error.code == 0) {
			reloadVitalSign(ticketId, patientId, vitalSignId, false);
			showMessage('resultMessage' + ticketId, _('Save successful'), 'success')
		} else {			
			showMessage('resultMessage' + ticketId, _('Save fail'), 'error')
		}
	}
	});


}

function loadTest(ticketId) {

}
/**
* move patient form emergency room to recovery room
* @param ticketId 
* @param patientName
* @return
* + Update gui
* + Show error if moving fail
*/
function movetoRecoveryRoom(ticketId, patientName) {	
	promptConfirm(_("Move to saving-room"),_('Are you sure moving patient <b>[{0}]</b> to saving-room?',patientName), function() {

		$.ajax({
			type:		"GET",
			url:		"../EmergencyInPatient/MoveToRecoveryAjax?set_ajax_view",
			data:		"ticketId=" + ticketId,		
			dataType:   "json",
			success: 	function(data) {

			if (data.error.code == 0) {
				viewDoctorQueue();
			} else {
				displayError(data.error.mess);
			}
		}
		});
		return true;
	},'YesNo','warn',_('No'));	

}
/**
* Display check out form
* @param ticketId
* @return display popup 
*/

function displaySelectCheckOutForm(ticketId) {
	var checkOutTypeHtml = '<table>';
	checkOutTypeHtml += "<tr>";
	checkOutTypeHtml +=  "<td ><input type='radio' name='checkOutType' id='checkOutHospital' value='0' checked='checked'>" + 
			"<label for='checkOutHospital'>" + _("Check-out Hospital") + "</label></td>";
	checkOutTypeHtml += "</tr>";

	checkOutTypeHtml += "<tr>";
	checkOutTypeHtml +=  "<td ><input type='radio' name='checkOutType' id='checkOutDepartment' value='1'>" + 
			"<label for='checkOutDepartment'>" + _("Change department") + "</label></td>";
	checkOutTypeHtml += "</tr>";

	checkOutTypeHtml += "<tr>";
	checkOutTypeHtml +=  "<td ><input type='radio' name='checkOutType' id='checkOutDeath' value='2'>" + 
			"<label for='checkOutDeath'>" + _("Death") + "</label></td>";
	checkOutTypeHtml += "</tr>";

	checkOutTypeHtml += '</table>';


	promptConfirm(_("Check-out"),checkOutTypeHtml, function() {
		var checkOutType = $("input:radio[name='checkOutType']:checked").val();
		if (checkOutType == 0) {
			displayEmerLeaveForm(ticketId);			
		} else if (checkOutType == 1) {
			displayEmerChangeDeptForm(ticketId);
		} else if (checkOutType == 2) {
			displayEmerDeathForm(ticketId);
		}

		return true;					
	},'NextCancel', null ,_('Next'));
}
/**
* display check out hospital in normal condition(alive)
* @param ticketId
* @return
* + check out hospital dialog
*/
function displayEmerLeaveForm(ticketId) {
	$.ajax({
		type:		"GET",
		url:		"../EmergencyInPatient/DisplayCheckOutLeaveAjax?set_ajax_view",
		data:		"ticketId=" + ticketId,		
		dataType:   "json",
		success: 	function(data) {
		if (data.error.code == 0) {			
			var buttons = {};
			buttons[_('Cancel')] = function() {
				$(this).dialog('close');		
			};
			buttons[_('Ok')] = function() {
				var dialog = $(this);
				if($('#icd10CodePrimary').text() == ''){
					displayError(_('Cannot check out, lack of ICD10 info!'));
					return;
				}
				promptConfirm(_("Check-out"),_('Are you sure checkout this patient?'), function() {
					dialog.dialog('close');
					processEmerCheckOutLeave(ticketId);	
					return true;					
				},'YesNo','warn',_('No'));

			};			
			generalDialog(null,_("Check-out Hospital"),data.result,null,{
				autoOpen: true,			
				bgiframe: true,
				resizable: false,
				modal: true,	
				width: 500,
				height: 280,
				buttons: buttons
			});
		} else {
			displayError(data.error.mess);
		}
	}
	});
}
/**
* display check out department
* @param ticketId
* @return
* + check out deparment dialog
*/
function displayEmerChangeDeptForm(ticketId) {
	$.ajax({
		type:		"GET",
		url:		"../EmergencyInPatient/DisplayCheckOutDeptAjax?set_ajax_view",
		data:		"ticketId=" + ticketId,		
		dataType:   "json",
		success: 	function(data) {
		if (data.error.code == 0) {

			var buttons = {};
			buttons[_('Cancel')] = function() {
				$(this).dialog('close');		
			};
			buttons[_('Ok')] = function() {
				var dialog = $(this);
				if($('#icd10CodePrimary').text() == ''){
					displayError(_('Cannot change department, lack of ICD10 info!'));
					return;
				}
				var toDepartmentId = $('#toDepartment :selected').val();				
				promptConfirm(_("Change Department"),_('Are you sure to move this patient to other department?'), function() {
					dialog.dialog('close');
					processEmerCheckOutChangeDept(ticketId, toDepartmentId);
					return true;					
				},'YesNo','warn',_('No'));

			};			
			generalDialog(null,_("Change Department"),data.result,null,{
				autoOpen: true,			
				bgiframe: true,
				resizable: false,
				modal: true,	
				width: 500,
				height: 330,
				buttons: buttons
			});
		} else {
			displayError(data.error.mess);
		}
	}
	});
}
/**
* display check out by death form
* @param ticketId
* @return
* + check out death dialog
*/
function displayEmerDeathForm(ticketId) {
	$.ajax({
		type:		"GET",
		url:		"../EmergencyInPatient/DisplayCheckOutDeathAjax?set_ajax_view",
		data:		"ticketId=" + ticketId,		
		dataType:   "json",
		success: 	function(data) {
		if (data.error.code == 0) {

			var buttons = {};
			buttons[_('Cancel')] = function() {
				$(this).dialog('close');		
			};
			buttons[_('Save')] = function() {
				if (!isReadyToSubmitDeath()) {
					return false;		
				}
				var dialog = $(this);
				promptConfirm(_("Confirm"),_('Do you confirm this patient died?'), function() {
					dialog.dialog('close');
					processEmerCheckOutDeath(ticketId, false);	
					return true;					
				},'YesNo','warn',_('No'));

			};	
			buttons[_('Save and print')] = function() {
				if (!isReadyToSubmitDeath()) {
					return false;		
				}
				var dialog = $(this);
				promptConfirm(_("Confirm"),_('Do you confirm this patient died?'), function() {
					dialog.dialog('close');
					processEmerCheckOutDeath(ticketId, true);	
					return true;					
				},'YesNo','warn',_('No'));

			};
			generalDialog(null,_("Death"),data.result,null,{
				autoOpen: true,			
				bgiframe: true,
				resizable: false,
				modal: true,	
				width: 840,
				height: 610,
				buttons: buttons
			});
		} else {
			displayError(data.error.mess);
		}
	}
	});

}
/**
* Do change department.
* @param ticketId
* @param toDepartmentId
* @return nothing.
*/
function processEmerCheckOutChangeDept(ticketId, toDepartmentId) {
	enumTreatmentResult = $('#treatmentResult :selected').val();

	$.ajax({
		type:		"GET",
		url:		"../EmergencyInPatient/CheckOutChangeDepartmentAjax?set_ajax_view",
		data:		"ticketId=" + ticketId + "&toDepartmentId=" + toDepartmentId + "&enumTreatmentResult=" + enumTreatmentResult,		
		dataType:   "json",
		success: 	function(data) {
		if (data.error.code == 0) {
			var buttons = {};
			buttons[_('Close')] = function() {
				viewDoctorQueue();
				$(this).dialog('close');				
			};
			generalDialog(null,_("Information"),_("Change department successfully"),null,{
				autoOpen: true,			
				bgiframe: true,
				resizable: true,
				modal: true,							
				buttons: buttons
			});

		} else {
			displayError(data.error.mess);
		}
	}
	});

}
/**
* Do check out for fatal.
* @param ticketId
* @return nothing
*/
function processEmerCheckOutDeath(ticketId, print) {
	if (!isReadyToSubmitDeath()) {
		return;		
	}
	var submitData = getDeadInsideInfo();
	if (submitData == null) {
		return;
	}
	$.ajax({
		type:		"GET",
		url:		"../EmergencyInPatient/CheckOutDeathAjax?set_ajax_view",
		data:		submitData + "&ticketId=" + ticketId,		
		dataType:   "json",
		success: 	function(data) {
		if (data.error.code == 0) {
			var buttons = {};
			buttons[_('Close')] = function() {
				viewDoctorQueue();
				$(this).dialog('close');				
			};
			generalDialog(null,_("Information"),_("Procedure for death patient is done"),null,{
				autoOpen: true,			
				bgiframe: true,
				resizable: true,
				modal: true,							
				buttons: buttons
			});
			if(print){
				printReportDeadInsite(data.deathInsideInfoId);
			}

		} else {
			displayError(data.error.mess);
		}
	}
	});
}
/**
* Do check out for leaving hospital.
* @param ticketId
* @return nothing
*/
function processEmerCheckOutLeave(ticketId) {
	enumTreatmentResult = $('#treatmentResult :selected').val();
	
	$.ajax({
		type:		"GET",
		url:		"../EmergencyInPatient/CheckOutLeaveAjax?set_ajax_view",
		data:		"ticketId=" + ticketId + "&enumTreatmentResult=" + enumTreatmentResult,		
		dataType:   "json",
		success: 	function(data) {
		if (data.error.code == 0) {
			var buttons = {};
			buttons[_('Close')] = function() {
				viewDoctorQueue();
				$(this).dialog('close');				
			};
			generalDialog(null,_("Information"),_("Check-out successfully"),null,{
				autoOpen: true,			
				bgiframe: true,
				resizable: true,
				modal: true,							
				buttons: buttons
			});

		} else {
			displayError(data.error.mess);
		}
	}
	});

}



function displayChangeRoomBed(ticketId, patientId, departmentId) {
	$.ajax({
		type:		"GET",
		url:		"../BedManagement/ArrangeBedForPatient?set_ajax_view",
		data:		"ticketId=" + ticketId + "&patientId=" + patientId + "&deptId=" + departmentId,		
		dataType:   "json",
		success: 	function(data) {
		if (data.error.code == 0) {
			var buttons = {};
			buttons[_('Close')] = function() {				
				$('#changeBedDialog').dialog('close');				
			};
			buttons[_('Change bed')] = function() {
				changeBed('changeBedDialog');				
			};
			$('#changeBedDialog').html(data.result);

			$('#viewBedStatusBtn').click(function() {
				viewBedStatus("bedStatusDialog");
			});
			generalDialog("changeBedDialog",null,null,null,{
				autoOpen: true,			
				bgiframe: true,
				resizable: true,
				modal: true,							
				buttons: buttons,
				width: 500,
				height: 300
			});

		} else {
			displayError(data.error.mess);
		}
	}
	});

}

/**
* Change bed for some patient.
*/
function changeBed(dialogId) {	
	$('#errorChangeBed').html('');
	//var roomId = $('select#roomListLbx  option:selected').val();
	//var bedId = $('select#bedListLbx  option:selected').val();
	//if (roomId == 'empty' || bedId == 'empty') {
	var bedId = $('#currentBedId').val();
	if (bedId == 'empty' || bedId == '') {
		$('#errorChangeBed').html("<font color='red'>" + _("Please select bed") + "</font>");

	} else if(bedId == 'nochange'){
		$("#" + dialogId).dialog('close');
	} else {
		promptConfirm(_("Confirm"),_('Are you sure to change bed for this patient?'), function() {		
			// call server to change bed for patient
			$.get(
					'../BedManagement/saveBedForPatient?set_ajax_view',
					{
						patientId: $('#patientId').val(),
						deptId:    $('#departmentId').val(),
						ticketId:  $('#ticketId').val(),
						newBedId:  bedId
					},
					function(data) {
						viewDoctorQueue();
						$("#" + dialogId).dialog('close');						
					}
			); 
			return true;
		},'YesNo','',_('Yes'));				
	}

}

function selectBed(bedId, bedCode, roomName){
	if($('#currentBedId').val() == bedId){
		$('#currentBedId').val('nochange');
	}
	else{
		$('#currentBedId').val(bedId);
	}
	$('#bedInfo').html(roomName + '/' + bedCode);
	$('#bedStatusDialog').dialog('close');
}


/**
* View the bed status at a specific department.
*/
function viewBedStatus() {
	$.get(
			'../BedManagement/viewBedStatus?set_ajax_view',
			{
				deptId: $('#departmentId').val()
			},
			function(data) {
				$('div#bedStatusDialog').html(data);								
				generalDialog('bedStatusDialog',_('Room/Bed status'),null,null,{
					autoOpen: true,			
					bgiframe: true,
					resizable: true,		
					width: 600,
					height: 400,
					modal: true
				});			
			}
	);
}

/**
* Get bed status of a specific room.  
*/
function getBedsOfRoom(roomId) {
	$.get(
			'../BedManagement/getBedsOfRoom?set_ajax_view',
			{
				roomId: roomId
			},
			function(data) {
				$('div#bedStatusDialog').html(data);				
			}
	);
}



function prepareGeneralDiagnosisData(ticketId) {
	var lcFloat = locale(decimalPoint, thousandSep, 1);
	var diagnosisGE = $('#diagnosisGE' + ticketId).val();
	var diagnosisGV = $('#diagnosisGV' + ticketId).val();
	var diagnosisGM = $('#diagnosisGM' + ticketId).val();
	var diagnosisPainful = $("input:radio[name='diagnosisPainful" + ticketId + "']:checked").val();
	var diagnosisGlu = parseLcNum($('#diagnosisGlu' + ticketId).val(), lcFloat);
	var diagnosisAllergy = $('#diagnosisAllergy' + ticketId).is(':checked') == true?1:0;
	var diagnosisAllergyDetail = $('#diagnosisAllergyDetail' + ticketId).val();
	var diagnosisDrugAllergyDetail = $('#diagnosisDrugAllergyDetail'+ticketId).val();
	var emrDoctor = $('#emrDoctor' + ticketId + ' :selected').val();
	var emrDiagnosis = $('#emrDiagnosis' + ticketId).val();
	var emrICD10Code = $('#emrICD10Code' + ticketId).val();
	var sndEmrICD10Code = $('#sndEmrICD10Code' + ticketId).val();
	
	var paras = 'ticketId=' + ticketId
	+ '&diagnosisGE=' + diagnosisGE
	+ '&diagnosisGV=' + diagnosisGV
	+ '&diagnosisGM=' + diagnosisGM 
	+ '&diagnosisPainful=' + diagnosisPainful
	+ '&diagnosisGlu=' + diagnosisGlu
	+ '&diagnosisAllergy=' + diagnosisAllergy
	+ '&diagnosisAllergyDetail=' + diagnosisAllergyDetail
	+ '&diagnosisDrugAllergyDetail=' + diagnosisDrugAllergyDetail
	+ '&emrDoctorId=' + emrDoctor
	+ '&emrDiagnosis=' + emrDiagnosis
	+ '&emrICD10Code=' + emrICD10Code
	+ '&sndEmrICD10Code=' + sndEmrICD10Code;
	return paras;	

}

function saveGeneralDiagnosis(ticketId) {
	var paras = prepareGeneralDiagnosisData(ticketId);

	$.ajax({
		type:		"GET",
		url:		"../GeneralDiagnosis/SaveGeneralDiagnosisAjax?set_ajax_view",
		data:		paras,		
		dataType:   "json",
		beforeSend:	function() {
			$('#generalDResultMessage' + ticketId).html('');				
		},
		success: 	function(data) {
			$('#emrICD10Code' + ticketId).css('border-color', '#AAA');
			$('#sndEmrICD10Code' + ticketId).css('border-color', '#AAA');
			if (data.error.code == 0) {
				$('#emrICD10Name' + ticketId).val(data.result.firstIcd10);
				$('#sndEmrICD10Name' + ticketId).val(data.result.secondIcd10);
				showMessage('generalDResultMessage' + ticketId, _('Save successful'), 'success')
			} else {
				if(data.error.mess.indexOf('ICD10') != -1){
					showMessage('generalDResultMessage' + ticketId, data.error.mess, 'error');
					$('#' + data.error.field).css('border-color', 'red');
					if(data.error.field.indexOf('sndEmrICD10Code') != -1){
						$('#emrICD10Name' + ticketId).val(data.result.firstIcd10);
						$('#sndEmrICD10Name' + ticketId).val('');						
					}
					else{
						$('#emrICD10Name' + ticketId).val('');
						$('#sndEmrICD10Name' + ticketId).val(data.result.secondIcd10);
					}
				}
				else{
					showMessage('generalDResultMessage' + ticketId, _('Save fail'), 'error');
				}
			}
		}
	});

}

function changeGCS(ticketId){
	var GCS	=	0;
	var E	=	Number($('#diagnosisGE'+ticketId).val());
	var V	=	Number($('#diagnosisGV'+ticketId).val());
	var M	=	Number($('#diagnosisGM'+ticketId).val());
	GCS 	= 	E + V + M;
	$('#glasgowEMVSpn'+ticketId).html('');
	$('#glasgowEMVSpn'+ticketId).html(GCS);
}

function changePainLevel(ticketId, painLevel){
	$('#painLevelSpn'+ticketId).html(painLevel);
}

function checkAllergy(ticketId){
	if($('#diagnosisAllergy' + ticketId).is(':checked') == true) {
        $('#diagnosisAllergyDetail' + ticketId).attr('disabled','');
        $('#diagnosisDrugAllergyDetail' + ticketId).attr('disabled', '');
        
    } else {
    	$('#diagnosisAllergyDetail' + ticketId).val('');
    	$('#diagnosisAllergyDetail' + ticketId).attr('disabled','disabled');
    	$('#diagnosisDrugAllergyDetail' + ticketId).val('');
    	$('#diagnosisDrugAllergyDetail' + ticketId).attr('disabled', 'disabled');
    }
}

function printReportDeadInsite(deathInfoId){
    var url='../MedicalPrintView/PrintReportDeadInside?set_print_view&deathInfoId=' + deathInfoId;
    window.open(url, '', 'scrollbars=yes, menubar=no, width=800, height=600, resizable=yes, toolbar=no, location=no, status=no');
}

function validateBP(BPs, BPd, messSpan){
	var lcInt = locale(decimalPoint, thousandSep, 0);
	var BPsVal = parseLcNum(BPs.val(),lcInt);
	var BPdVal = parseLcNum(BPd.val(),lcInt);
	
	messSpan.css('color', 'green');
	messSpan.html('');
	BPs.css('border-color', '#AAA');
	BPd.css('border-color', '#AAA');
	
	if(BPs.val() == '' && BPd.val() == ''){
		return true;
	}
	else if(BPs.val() == ''){
		messSpan.css('color', 'red');
		messSpan.html(_("Field BPs is empty?"));
		BPs.css('border-color', 'red');
		return false;
	}
	else if(BPd.val() == ''){
		messSpan.css('color', 'red');
		messSpan.html(_("Field BPd is empty?"));
		BPd.css('border-color', 'red');
		return false;
	}
	else{
		if(BPsVal < BPdVal){
			messSpan.css('color', 'red');
			messSpan.html(_("BPs < BPd?"));
			BPs.css('border-color', 'red');
			BPd.css('border-color', 'red');
			return false;
		}
		else{
			return true;
		}
	}
}